package toolkit

import (
	"archive/zip"
	"fmt"
	"io"
	"log"
	"os"
	"path/filepath"
)

func appendFiles(filename string, zw *zip.Writer) error {
	file, err := os.Open(filename)
	if err != nil {
		return fmt.Errorf("Failed to open %s: %s", filename, err)
	}
	defer file.Close()

	relativeFilename := filepath.Base(file.Name())
	wr, err := zw.Create(relativeFilename)
	if err != nil {
		return fmt.Errorf("Failed to create entry for %s in zip file: %s", filename, err)
	}

	if _, err := io.Copy(wr, file); err != nil {
		return fmt.Errorf("Failed to write %s to zip: %s", filename, err)
	}

	return nil
}

func ZipWriter(w io.Writer, files []string) {
	zw := zip.NewWriter(w)
	defer zw.Close()
	for _, filename := range files {
		if err := appendFiles(filename, zw); err != nil {
			log.Fatalf("Failed to add file %s to zip: %s", filename, err)
		}
	}
}
